//
//  IllnessViewController.m
//  安好
//
//  Created by lianchuang on 14-11-13.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "IllnessViewController.h"
#import "SystemSettingTableViewCell.h"
#import "IllnessDetailViewController.h"
#import "IllnessModel.h"
#import "RegDoctorListViewController.h"
#import "PopoverView.h"
#import "CheckDepartmentModel.h"

#define RGB(r, g, b)    [UIColor colorWithRed:(r)/255.f green:(g)/255.f blue:(b)/255.f alpha:1.f]

@interface IllnessViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UIView *_filterView;
    FKSearchBar * illSeachBar;
    BOOL departmentBool;
}
@property (nonatomic, strong) UITableView *leftTableView;

@property (nonatomic, strong) UITableView *rightTableView;
// 控制右边的数据
@property (nonatomic, strong) NSMutableArray *rightTableArr;
@property (nonatomic, strong) NSString *seekStr;

@property (nonatomic, strong) UITableViewCell *rightViewCell;
@property (nonatomic, strong) UIView *maskViews;

// 控制线条的
@property (nonatomic, strong) UIView *transverseLineView;
@property (nonatomic, strong) UIView *shotVerticalLineView;
@property (nonatomic, strong) UIView *longVerticalLineView;
@end

@implementation IllnessViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.illPage = 1;
    self.illnessArray = [[NSMutableArray alloc]init];
    [self makeNavBar];
    [self loadData];
    if (self.isFromMyFoucus) {
    }else{
        [self markIllnessSearchBar];
    }
    [self makeIllnessTableView];
    [self makeTableView];
}
#pragma - mark searchBar
- (void)markIllnessSearchBar
{
    illSeachBar = [[FKSearchBar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    illSeachBar.searchTextField.placeholder = @"疾病";
    illSeachBar.fkSearchRequestDelegate = self;
    [self.view addSubview:illSeachBar];
}
#pragma - mark tableView
/**
 *  加载tableView
 */
- (void)makeIllnessTableView
{
    if (self.isFromMyFoucus) {
        self.illnessTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight - iOS7TopMargin) style:UITableViewStyleGrouped];
    }else{
    self.illnessTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,44, kScreenWidth, kScreenHeight - iOS7TopMargin - 44) style:UITableViewStyleGrouped];
    }
    
    self.illnessTableView.delegate = self;
    self.illnessTableView.dataSource = self;
    self.illnessTableView.showsHorizontalScrollIndicator = NO;
    self.illnessTableView.showsVerticalScrollIndicator = NO;
    [self.illnessTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉系统的分割线
    [self.illnessTableView setSeparatorColor:[UIColor colorWithRed:228.0/255 green:228.0/255 blue:228.0/255 alpha:1]];
    [self.illnessTableView addFooterWithTarget:self action:@selector(loadData)];
    [self.view addSubview:self.illnessTableView];
}

-(void)makeNavBar
{
    self.navigationItem.title = @"疾病";
    // “返回”
    UIBarButtonItem *backBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBackDown)];
    backBtnItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnItem;
    // “筛选”
    if (self.isFromMyFoucus) {
        
    }else{
    UIButton *rightButtonMore = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButtonMore.frame = CGRectMake(0,0, 23, 23);
    [rightButtonMore setImage:[UIImage imageNamed:@"公用_更多@2x.png"] forState:UIControlStateNormal];
    [rightButtonMore addTarget:self action:@selector(showListView:) forControlEvents:UIControlEventTouchUpInside];
    [self makeRightFilterItem];
    }
}
- (void)showListView:(UIButton *)sender
{
}
-(void)makeRightFilterItem
{
    UIBarButtonItem *filterBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_筛选.png"] style:UIBarButtonItemStylePlain target:self action:@selector(filterBtnDown)];
    filterBtnItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = filterBtnItem;
}
//“完成”
-(void)makeRightFilterFinishItem
{
    UIBarButtonItem *filterBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_完成.png"] style:UIBarButtonItemStylePlain target:self action:@selector(filterFinishDown)];
    filterBtnItem.tintColor = [UIColor whiteColor];
    filterBtnItem.tag = 100;
    self.navigationItem.rightBarButtonItem = filterBtnItem;
}

//返回 百科页面
-(void)leftBackDown
{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  点击“筛选” 按钮图标换成“完成”
 *   下拉-选项列表 
 */
-(void)filterBtnDown
{
    
    [self makeRightFilterFinishItem];
    [self loadDataDepartment];
//    [UIView animateWithDuration:0.2 animations:^{
       self.leftTableView.frame = CGRectMake(0, 0, kScreenWidth / 3, 200);
         self.rightTableView.frame = CGRectMake(kScreenWidth/3, 0, kScreenWidth/3 * 2, 200);
        self.longVerticalLineView.frame = CGRectMake(kScreenWidth / 3 - 0.5, 45, 0.5, 155);
//    }];
    self.illPage = 1;
    departmentBool = YES;
    [self.view addSubview:self.maskViews];
    [self.view addSubview:self.transverseLineView];
    [self.view addSubview:self.shotVerticalLineView];
    [self.view addSubview:self.longVerticalLineView];
    
//    _filterView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth/2.0, 0, kScreenWidth/2.0, 0)];
//    _filterView.backgroundColor = [UIColor grayColor];
//    [self.view addSubview:_filterView];
//    [UIView animateWithDuration:0.25 animations:^{
//        _filterView.frame = CGRectMake(kScreenWidth/2.0, 64, kScreenWidth/2.0, 200);
//    }];
    
    
}
/**
 *  点击"完成"图标变回“筛选” 
 *  选项列表收回  
 */
-(void)filterFinishDown
{
    [self makeRightFilterItem];
    
//    [UIView animateWithDuration:0.2 animations:^{
        self.leftTableView.frame = CGRectMake(0, -200, kScreenWidth / 3, 200);
        self.rightTableView.frame = CGRectMake(kScreenWidth/3,-200, kScreenWidth/3 * 2, 200);
        self.longVerticalLineView.frame = CGRectMake(kScreenWidth / 3, 45, 0, 0);
//    }];
    [self.maskViews removeFromSuperview];
    [self.transverseLineView removeFromSuperview];
    [self.shotVerticalLineView removeFromSuperview];
    [self.longVerticalLineView removeFromSuperview];
    [self.illnessArray removeAllObjects];
    [self loadData];
    

//    [UIView animateWithDuration:0.25 animations:^{
//        _filterView.frame = CGRectMake(kScreenWidth/2.0, 64, kScreenWidth/2.0, 0);
//    }];
    
}

- (void)packUpView{
    [self makeRightFilterItem];
//    [UIView animateWithDuration:0.2 animations:^{
        self.leftTableView.frame = CGRectMake(0, -200, kScreenWidth / 3, 200);
        self.rightTableView.frame = CGRectMake(kScreenWidth/3,-200, kScreenWidth/3 * 2, 200);
//    }];
    [self.maskViews removeFromSuperview];
    [self.transverseLineView removeFromSuperview];
    [self.shotVerticalLineView removeFromSuperview];
    [self.longVerticalLineView removeFromSuperview];
}

#pragma mark - 数据加载
-(void)loadData
{
    
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    if ([self.searchIllness length] == 0){
        
    }else{
        [dict setObject:self.searchIllness forKey:@"keyword"];
    }
    NSString *isFromMyFocuse;
    if (self.isFromMyFoucus) {
        isFromMyFocuse = [NSString stringWithFormat:@"collection/list/"];
        [dict setObject:@"1" forKey:@"type"];
    } else if (self.isFromBaike){
        isFromMyFocuse = [NSString stringWithFormat:@"wiki/diseaseList/"];
        [dict setObject:self.hosid forKey:@"departmentid"];
    }else if (self.isFromDrug){
        isFromMyFocuse = [NSString stringWithFormat:@"wiki/diseasebydrugid/"];
        [dict setObject:self.hosid forKey:@"drugid"];
    }else if (departmentBool){
//        if ([[dict objectForKey:@"keyword"] length] != 0) {
//            [dict removeObjectForKey:@"keyword"];
//        }
        isFromMyFocuse = [NSString stringWithFormat:@"wiki/diseaseList/"];
        if (![self.seekStr isEqualToString:@"全部"]&& self.seekStr.length != 0) {
            [dict setObject:self.seekStr forKey:@"departmentid"];
        }
    }else{
        isFromMyFocuse = [NSString stringWithFormat:@"wiki/diseaseList/"];
    }
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:[NSString stringWithFormat:@"%ld",self.illPage] forKey:@"page"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,isFromMyFocuse] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            if (self.illPage == 1){
            [self shouLabel:@"暂无内容"];
            self.illnessTableView.hidden = YES;
            }
            [self.illnessTableView reloadData];
            [self.illnessTableView footerEndRefreshing];
        }else{
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            self.illnessTableView.hidden = NO;
//            if (self.isSearch == YES){
//                if ([self.illnessArray count] != 0){
//                    [self.illnessArray removeAllObjects];
//                }
//            }
            if (jsonDictArr!=nil) {
                self.illPage++;
                for (NSDictionary * dic in jsonDictArr){
                    [self.illnessArray addObject:dic];
                }
                [self.illnessTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];//去掉系统的分割线
                if ([self.illnessArray count] <= 9) {
                }
                [self.illnessTableView reloadData];
            }else if ([jsonDictArr count] < 20){
                [self.illnessTableView footerEndRefreshing];
            }else{
                if (self.illPage>1) {
                    MyNSLog("下拉无数据");
                }
            }
            
        }
        if (self.illnessArray.count != 0) {
            [self shouLabel:@""];
        }
        [self.illnessTableView reloadData];
        [self.illnessTableView footerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self.illnessTableView footerEndRefreshing];
    }];
}
#pragma mark 2中cell的加载
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.leftTableView) {
        return 1;
    }
    if (tableView == self.rightTableView) {
        return self.rightTableArr.count + 1;
    }
    if (tableView == self.illnessTableView) {
        MyNSLog("==========%d",self.illnessArray.count);
        return [self.illnessArray count];
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.leftTableView) {
        return 35;
    }
    if (tableView == self.rightTableView) {
        return 35;
    }
    if (kScreenWidth == 414){
        return 56;
    }else{
    return 44;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.leftTableView) {
        return 10;
    }
    if (tableView == self.rightTableView) {
        return 10;
    }
    if (tableView == self.illnessTableView) {
        return 0.01;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (tableView == self.leftTableView) {
        return 5;
    }
    if (tableView == self.rightTableView) {
        return 5;
    }
    if (tableView == self.illnessTableView) {
        return 0.01;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
    view.backgroundColor = [UIColor lightGrayColor];
       if (tableView == self.leftTableView) {
           
        view.backgroundColor = RGB(248, 248, 248);
        return view;
    }
    if (tableView == self.rightTableView) {
        view.backgroundColor = RGB(238, 238, 238);
        return view;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
    view.backgroundColor = [UIColor lightGrayColor];
    if (tableView == self.leftTableView) {
        view.backgroundColor = RGB(248, 248, 248);
        return view;
    }
    if (tableView == self.rightTableView) {
        view.backgroundColor = RGB(238, 238, 238);
        return view;
    }
    return nil;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.illnessTableView) {
        NSDictionary * illDic = [self.illnessArray objectAtIndex:indexPath.row];
        SystemSettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SystemSettingTableViewCell"];
        if (cell == nil) {
            if (kScreenWidth == 414){
                cell = [[[NSBundle mainBundle] loadNibNamed:@"SystemSettingTableViewCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"SystemSettingTableViewCell" owner:self options:nil] firstObject];

            }
        }
        cell.pushImageView.hidden = YES;
        cell.settingLabel.text = [illDic objectForKey:@"diseasename"];

        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
    if (tableView == self.rightTableView) {
        static NSString *indentify = @"rightCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentify];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentify];
        }
        
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.backgroundColor = RGB(238, 238, 238);
        if (indexPath.row == 0) {
            cell.textLabel.text = [NSString stringWithFormat:@"   全部"];
        }else{
            CheckDepartmentModel *model = [self.rightTableArr objectAtIndex:indexPath.row - 1];
            cell.textLabel.text = [NSString stringWithFormat:@"   %@",model.departmentname];
        }
        return cell;
    }
    
    if (tableView == self.leftTableView) {
        static NSString *indentify = @"leftCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentify];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentify];
        }

        cell.textLabel.text = @"   科室";
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.backgroundColor = RGB(238, 238, 238);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.rightTableView) {
        if (indexPath.row == 0) {
            self.seekStr = [NSString stringWithFormat:@"全部"];
        }else{
            CheckDepartmentModel *model = self.rightTableArr[indexPath.row -1];
            self.seekStr = [NSString stringWithFormat:@"%@",model.departmentid];
        }
        self.rightViewCell.contentView.backgroundColor = RGB(238, 238, 238);
        MyNSLog("%@", self.seekStr);
        [self.rightTableView cellForRowAtIndexPath:indexPath].contentView.backgroundColor = RGB(226, 226, 226);;
        
        self.rightViewCell = [self.rightTableView cellForRowAtIndexPath:indexPath];
        return;
    }
    if (tableView == self.leftTableView) {
        return;
    }
    
    if ([self.fromReg isEqualToString:@"挂号疾病"]) {
        NSDictionary * illDic = [self.illnessArray objectAtIndex:indexPath.row];
        RegDoctorListViewController * doclist = [[RegDoctorListViewController alloc] init];
        doclist.regHosDepartDic = @{@"diseaseid":illDic[@"diseaseid"]};
        [self.navigationController pushViewController:doclist animated:YES];
    }else{
    
        NSDictionary * illDic = [self.illnessArray objectAtIndex:indexPath.row];
        IllnessDetailViewController *illnessDetailViewController = [[IllnessDetailViewController alloc]init];
        illnessDetailViewController.isload = NO;
        illnessDetailViewController.diseaseid = [illDic objectForKey:@"diseaseid"];
        illnessDetailViewController.diseasename = [illDic objectForKey:@"diseasename"];
        [self.navigationController pushViewController:illnessDetailViewController animated:YES];
    
    }
  
}
#pragma - mark FKSearchDelegate
/**
 *  FKSearch的delegate
 */
- (void)VoiceConversion
{
    [illSeachBar.searchTextField resignFirstResponder];
    [self starVoice];
}
- (void)voice:(NSString *)voice
{
    [self.illnessArray removeAllObjects];
    illSeachBar.searchTextField.text = voice;
    departmentBool = NO;
    self.isSearch = YES;
    self.illPage = 1;
    self.searchIllness = voice;
    [self loadData];
}
- (void)SearchString
{
    [self.illnessArray removeAllObjects];
    [illSeachBar.searchTextField resignFirstResponder];
    departmentBool = NO;
    self.isSearch = YES;
    self.illPage = 1;
    self.searchIllness = illSeachBar.searchTextField.text;
    [self loadData];

}



#pragma mark - 筛选数据 -

-(void)makeTableView
{
    
    self.LeftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -200, kScreenWidth / 3, 0)];
    self.leftTableView.backgroundColor = RGB(248, 248, 248);
    [self.view addSubview:self.leftTableView];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.leftTableView.showsHorizontalScrollIndicator = NO;
    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    
    //左边的table
    self.RightTableView = [[UITableView alloc] initWithFrame:CGRectMake(kScreenWidth/3, -200, kScreenWidth/3 * 2, 0)];
    [self.view addSubview:self.rightTableView];
    self.rightTableView.delegate = self;
    self.rightTableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.rightTableView.showsHorizontalScrollIndicator = NO;
    self.rightTableView.showsVerticalScrollIndicator = NO;
    self.rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.rightTableView.backgroundColor = RGB(238, 238, 238);


}


#pragma mark - 数据加载
-(void)loadDataDepartment
{
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setValue:@"2" forKey:@"returnType"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@wiki/department/",kBaseURL] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            if (self.illPage == 1){
                [self shouLabel:@"暂无内容"];
            }
        }else{
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            for (NSDictionary *objc in jsonDictArr) {
                CheckDepartmentModel *model = [[CheckDepartmentModel alloc] init];
                [model setValuesForKeysWithDictionary:objc];
                [self.rightTableArr addObject:model];
            }
        }
        [self.rightTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
    }];
    
}


#pragma mark - 懒加载 - 
- (UIView *)transverseLineView{
    if (_transverseLineView == nil) {
        _transverseLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 199.5, kScreenWidth, 0.5)];
        _transverseLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
    }
    return _transverseLineView;
}

- (UIView *)shotVerticalLineView{
    if (_shotVerticalLineView == nil) {
        _shotVerticalLineView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth / 3 - 0.5 , 0, 0.5, 10)];
        _shotVerticalLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
    }
    return _shotVerticalLineView;
}

- (UIView *)longVerticalLineView{
    if (_longVerticalLineView == nil) {
        _longVerticalLineView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth / 3 - 0.5, 45, 0.5, 155)];
        _longVerticalLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
    }
    return _longVerticalLineView;
}

- (UIView *)maskViews{
    if (_maskViews == nil) {
        _maskViews = [[UIView alloc] initWithFrame:CGRectMake(0, 200, kScreenWidth, kScreenHeight - 264)];
        _maskViews.alpha = 0.5;
        _maskViews.backgroundColor = [UIColor lightGrayColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(packUpView)];
        tap.numberOfTapsRequired = 1;
        [_maskViews addGestureRecognizer:tap];
    }
    return _maskViews;
}

- (UITableViewCell *)rightViewCell{
    if (_rightViewCell == nil) {
        _rightViewCell = [[UITableViewCell alloc] init];
    }
    return _rightViewCell;
}

- (NSMutableArray *)rightTableArr{
    if (_rightTableArr == nil) {
        self.rightTableArr = [NSMutableArray array];
    }
    return _rightTableArr;
}



@end
